from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinLengthValidator, FileExtensionValidator
from utils.modelMixin import timeFiledMixin, statusFiledMixin
from utils.validators import validate_image_size


class ProductType(timeFiledMixin.CreateAndUpdateTimeFiled, models.Model):
    PRODUCT_CATEGORIES = (
        ("APP", "移动应用"),
        ("WEB", "网页应用"),
        ("API", "接口服务"),
        ("ALL", "综合类型"),
    )

    name = models.CharField(
        max_length=200, verbose_name="类型名称", help_text="产品分类名称（如：电商系统）"
    )

    category = models.CharField(
        max_length=8, verbose_name="技术分类", choices=PRODUCT_CATEGORIES, default="API"
    )

    class Meta:
        db_table = "cool_product_type"
        verbose_name = "产品类型表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Products(timeFiledMixin.CreateAndUpdateTimeFiled, statusFiledMixin.ActiveFiled):
    name = models.CharField(
        max_length=200,
        verbose_name="产品名称",
        unique=True,
        validators=[MinLengthValidator(3)],  # 添加验证器
    )

    logo = models.ImageField(
        upload_to="products/logo/%Y/%m/%d/",  # 按日期分目录
        verbose_name="品牌标识",
        validators=[
            FileExtensionValidator(["png", "jpg", "svg"]),  # 文件类型限制
            validate_image_size,  # 自定义图片尺寸验证
        ],
    )
    description = models.CharField(
        max_length=255, verbose_name="产品介绍", blank=True, null=True
    )

    product_type = models.ForeignKey(
        ProductType,
        on_delete=models.PROTECT,  # 防止误删关联类型
        verbose_name="所属分类",
        related_name="products_type",
    )

    # 关系字段优化
    administrators = models.ManyToManyField(
        User, verbose_name="管理员", related_name="managed_users", blank=True
    )

    creator = models.ForeignKey(
        User,
        verbose_name="创建者",
        related_name="created_products",
        on_delete=models.SET_NULL,
        null=True,
    )

    class Meta:
        db_table = "cool_product"
        verbose_name = "产品"
        verbose_name_plural = verbose_name
        models.Index(fields=["active"], name="idx_active_products")
        # 创建时间索引
        models.Index(fields=["-create_time"], name="idx_new_products"),

    def __str__(self):
        return self.name


class ProductAuditLog(models.Model):
    """审计日志"""

    ACTION_CHOICES = (("CREATE", "创建"), ("UPDATE", "更新"), ("ARCHIVE", "归档"))

    product = models.ForeignKey(Products, on_delete=models.CASCADE)
    operator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    action = models.CharField(max_length=10, choices=ACTION_CHOICES)
    detail = models.JSONField()
    timestamp = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "cool_product_audit_log"
        verbose_name = "产品审计日志"
        verbose_name_plural = verbose_name
